package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojo.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    @Autowired
    private ApUserMapper apUserMapper;
    /**
     * 用户登录功能实现
     * @param loginDto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto loginDto) {
        //1.用户登录（手机号+密码）
        //1.1判断用户输入信息是否存在
        if (StringUtils.isNotBlank(loginDto.getPhone()) && StringUtils.isNotBlank(loginDto.getPassword())){
            //1.2根据用户名查询用户信息
            ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, loginDto.getPhone()));
            //1.3判断查询的用户是否存在
            if (apUser == null){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
            }
            //1.4比对用户密码
            //获取用户密码中的盐，和用户输入的密码得到加密的密码
            String salt = apUser.getSalt();
            String hex = DigestUtils.md5DigestAsHex((loginDto.getPassword() + salt).getBytes());
            if (!hex.equals(apUser.getPassword())){
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //1.5返回数据(生成token返回)
            //生成token
            String token = AppJwtUtil.getToken(Long.valueOf(apUser.getId()));
            //封装数据
            Map<String, Object> result = new HashMap<>();
            result.put("token",token);
            apUser.setPassword("");
            apUser.setSalt("");
            result.put("apUser",apUser);
            //返回结果
            return  ResponseResult.okResult(result);
        }
        //2.匿名登录
        //2.1生成token,id为0
        String token = AppJwtUtil.getToken(0L);
        //2.2封装结果返回
        Map<String, Object> result = new HashMap<>();
        result.put("token",token);
        return ResponseResult.okResult(result);
    }


//    public static void main(String[] args) {
//        String s = DigestUtils.md5DigestAsHex(("123456" + "123abc").getBytes());
//        System.out.println(s);
//    }
}
